import pygame
import random


class Point():
    row = 0  # 行
    col = 0  # 列

    def __init__(self, row, col):
        self.row = row
        self.col = col

    def copy(self):
        return Point(self.row, self.col)

# 绘制一个窗口
WIDTH = 800  # 像素  宽
HEIGHT = 600  # 像素  高

ROW = 30  # 行
COL = 40  # 列

window = pygame.display.set_mode((WIDTH, HEIGHT))  # 定义了一个窗口，值是用元组封装好的

pygame.display.set_caption("贪吃蛇")                # 定义窗口标题

BG_COLOR = (40, 40, 60)  # 背景颜色 RGB

head = Point(row=int(ROW/2), col=int(COL/2))  # 蛇头的坐标
HEAD_COLOR = (220, 220, 220)  # 蛇头的颜色

food = Point(row=random.randint(0, ROW-1), col=random.randint(0, COL-1))
FOOD_COLOR = (255, 100, 100)

snakes = [

    Point(row=head.row, col=head.col+1),
    Point(row=head.row, col=head.col+2),
    Point(row=head.row, col=head.col+3),
]

SNAKE_COLOR = (230, 230, 230)

# 画点
def draw_point(point, color):
    # 一行有多高
    cell_height = HEIGHT / ROW
    # 一列有多宽
    cell_width = WIDTH / COL
    # 在第几列画
    top = point.row * cell_height
    # 在第几行画
    left = point.col * cell_width

    pygame.draw.rect(window, color, (left, top, cell_width, cell_height))


move = 'left'
game = True

# 帧数设置
clock = pygame.time.Clock()
while game:
    # 事件 按了一下键盘就是一次事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print("结束")
            game = False    # 循环结束则整个程序结束
        if event.type == pygame.KEYDOWN:
            # w
            if event.key == 119:
                if move != 'down':
                    move = 'up'
            elif event.key == 115:
                if move != 'up':
                    move = 'down'
            elif event.key == 97:
                if move != 'right':
                    move = 'left'
            elif event.key == 100:
                if move != 'left':
                    move = 'right'

    # 移动蛇
    if move == 'up':
        head.row -= 1
    elif move == 'down':
        head.row += 1
    elif move == 'left':
        head.col -= 1
    elif move == 'right':
        head.col += 1

    # 是否死亡
    dead = False
    if head.row < 0 or head.col < 0 or head.row > ROW or head.col > COL:\
        dead = True

    for s in snakes:
        if s.row == head.row and s.col == head.col:
            dead = True

    if dead:
        game = False
        print("游戏结束")

    eat = head.row == food.row and head.col == food.col
    if eat:
        food = Point(row=random.randint(0, ROW - 1), col=random.randint(0, COL - 1))

    snakes.insert(0, head.copy())  # 将蛇头的上一次循环的坐标，插入到蛇的身体前面
    if not eat:
        snakes.pop()  # 删除列表中的最后一个元素

    # 1.在那个窗口画，2.颜色， 3，大小
    pygame.draw.rect(window, BG_COLOR, (0, 0, WIDTH, HEIGHT))  # 画矩形

    # 画蛇头
    draw_point(head, HEAD_COLOR)

    for s in snakes:
        draw_point(s, SNAKE_COLOR)

    # 画食物
    draw_point(food, FOOD_COLOR)

    # 函数，用来解决一些重复的工作
    pygame.display.flip()  # 更新屏幕
    # 帧数
    clock.tick(10)